package com.example.demo17;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
     private final int TAKE_PHOTO = 1;
     private Button sendNotification;
     private Button openCamera;
     private ImageView photo;
     private Uri imageUri;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendNotification = findViewById(R.id.send_notification);
        openCamera = findViewById(R.id.open_camera);
        photo = findViewById(R.id.photo);
        openCamera.setOnClickListener(new OpenCameraListener());




    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    try {
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        photo.setImageBitmap(bitmap);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            default:
                break;
        }
    }

    /**
     * 打开相机
     */
    class OpenCameraListener implements View.OnClickListener{
        @Override
        public void onClick(View v) {

            File outImage=new File(getExternalCacheDir(),"output_image.jpg");
            try {
                if (outImage.exists()){
                    outImage.delete();
                }
                outImage.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (Build.VERSION.SDK_INT >= 24){
                imageUri = FileProvider.getUriForFile(getApplicationContext(), "com.example.demo17.fileprovider", outImage);
            }else {
                imageUri = Uri.fromFile(outImage);
            }
            Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
            intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
            startActivityForResult(intent,TAKE_PHOTO);
        }
    }
}
